// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type {NextApiRequest, NextApiResponse} from 'next'

const crypto = require('crypto');

type Data = {
  decryptArray: any[]
}

export default function handler(
  req: NextApiRequest,
  res: NextApiResponse<Data | {}>
) {
  const requestBody = req.body;
  if (!requestBody.privateKey || !Array.isArray(requestBody.data)) {
    res.status(401).json({});
  }
  const processArray = requestBody.data || [];
  const decryptArray = processArray.map(item => {
    let value;
    try{
      value = crypto.privateDecrypt(requestBody.privateKey, Buffer.from(item.value, 'base64')).toString() || item.value;
    } catch (error) {
      console.log('decrypt error', item.value);
      value = item.value;
    }
    return {recordId: item.recordId, value: value}
  });
  res.status(200).json({decryptArray})
}
